package com.sks.web.action.privilege;

import java.io.StringWriter;
import java.sql.Date;
import java.util.Calendar;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.stereotype.Controller;

import com.sks.bean.pojo.Users;
import com.sks.mail.EmailSender;
import com.sks.service.privilege.UsersService;
import com.sks.utils.MD5;
import com.sks.web.formbean.privilege.UsersForm;
/**
 * 找回密码
 */
@Controller("/sks/privilege/users/post")
public class FindPasswordAction extends DispatchAction {
	// 修改密码链接的有效时间 30*60 秒（30分钟）
	private static int LIMITED_TIME = 30*60;
	
	@Resource UsersService usersService;
	/**
	 * 找回密码之发送邮件
	 */
	public ActionForward getpassword(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UsersForm formbean = (UsersForm) form;
		if(formbean.getLoginName()!=null && !"".equals(formbean.getLoginName().trim())){
			if(usersService.exist(formbean.getLoginName().trim())){
				Users users = usersService.findByLoginName(formbean.getLoginName().trim());
				//记录请求找回密码的时间
				Calendar cd = Calendar.getInstance();
				users.setChangePwdTime(cd.getTime());
				usersService.save(users);
				
				Template template = Velocity.getTemplate("mailContent.html");
				VelocityContext context = new VelocityContext();
				context.put("username", users.getLoginName());
				context.put("validateCode", MD5.MD5Encode(users.getLoginName()+ users.getLoginPwd()));
				StringWriter writer = new StringWriter(); 
				template.merge(context, writer);
				String content = writer.toString();
				EmailSender.send(users.getEmail(), "三棵松房地产中介--找回密码邮件", content, "text/html");
				return mapping.findForward("findpassword2");
			}else{
				request.setAttribute("message", "用户不存在");
			}			
		}/*else{
			request.setAttribute("message", "请输入用户名");
		}*/
		return mapping.findForward("findpassword");
	}
	
	/**
	 * 找回密码之显示密码修改界面
	 */
	public ActionForward update(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UsersForm formbean = (UsersForm) form;
		if(formbean.getLoginName()!=null && !"".equals(formbean.getLoginName().trim())){
			if(usersService.exist(formbean.getLoginName().trim())){
				Users users = usersService.findByLoginName(formbean.getLoginName().trim());
				String code = MD5.MD5Encode(users.getLoginName()+ users.getLoginPwd());
				if(code.equals(formbean.getValidateCode())){//校验通过，表示来源合法	
					java.util.Date startTime = users.getChangePwdTime();
					// 时间不存在，即并不是通过合法流程进行找回密码
					if(null ==startTime){
						return mapping.findForward("errorresult");
					}
					
					Calendar cd = Calendar.getInstance();
					java.util.Date endTime = cd.getTime();
					long diff = (endTime.getTime() - startTime.getTime())/1000;
					System.out.println(diff);
					if(diff > LIMITED_TIME){
						return mapping.findForward("errorresult");	
					}
					
					
					return mapping.findForward("findPassword3");
				}
			}			
		}
		return mapping.findForward("errorresult");
	}
	
	/**
	 * 找回密码之修改密码
	 */
	public ActionForward changepassword(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		UsersForm formbean = (UsersForm) form;
		if(formbean.getLoginName()!=null && !"".equals(formbean.getLoginName().trim())){
			if(usersService.exist(formbean.getLoginName().trim())){
				Users buyer = usersService.findByLoginName(formbean.getLoginName().trim());
				String code = MD5.MD5Encode(buyer.getLoginName()+ buyer.getLoginPwd());
				if(code.equals(formbean.getValidateCode())){//校验通过，表示来源合法					
					//usersService.updatePassword(buyer.getLoginName(), formbean.getLoginPwd().trim());
					// 清除找回密码链接的有效起始时间
					Users user = usersService.findByLoginName(formbean.getLoginName().trim());
					Calendar cd = Calendar.getInstance();
					user.setChangePwdTime(null);
					user.setLastUpdateTime(cd.getTime());
					// update password
					String pwd = formbean.getLoginPwd().trim();
					user.setLoginPwd(MD5.MD5Encode(pwd));
					
					usersService.update(user);
					
					request.setAttribute("message", "密码修改成功");
					request.setAttribute("urladdress", "/sks/privilege/users/logon.do");
					return mapping.findForward("message");
				}
			}			
		}
		return mapping.findForward("errorresult");
	}
}
